﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZenHR.AttData.Collection.AttDataRun;
using ZenHR.AttData.Collection.DataEntity;
using ZenHR.AttData.Collection.TaskQueue;
using ZenHR.AttData.Collection.Util;
using ZenHR.AttData.DAL;

namespace ZenHR.AttData.Collection
{
   public class TaskRun
    {
        static TaskQueue<TaskRunTimeInfo> taskQueue;

        public static  void Run(string task_id) {
            taskQueue = new TaskQueue<TaskRunTimeInfo>();

            #region 批量提交任务，异步批量多线程消费队列
            Task.Run(() =>
            {
                try
                {
                    var _RunByService = true;

                    //创建轮询监控（将到了时间点且当天未执行的采集任务插入待执行队列）
                    while (_RunByService)
                    {
                        Thread.Sleep(10000);   //这注意不要把间隔改太小了，生产环境的话建议1分钟

                        BaseDAL _BaseDAL = new BaseDAL();

                        var dt = _BaseDAL.GetTaskRunTimeInfo(task_id);
                        if (dt.Rows.Count > 0)
                        {

                            //如手工执行，则让服务不轮询既可
                            if (task_id != "")
                            {
                                _RunByService = false;
                            }

                            Console.WriteLine("insert-----Task Block!");

                            foreach (DataRow item in dt.Rows)
                            {
                                var _TaskRunTimeInfo = new TaskRunTimeInfo();
                                _TaskRunTimeInfo.Id = string.Format("{0}", item["id"]);
                                _TaskRunTimeInfo.Task_code = string.Format("{0}", item["task_code"]);
                                _TaskRunTimeInfo.Run_time = string.Format("{0}", item["run_time"]);
                                _TaskRunTimeInfo.Sql_type = string.Format("{0}", item["sql_type"]);
                                _TaskRunTimeInfo.ConnectionString = string.Format("{0}", item["connectionString"]);
                                _TaskRunTimeInfo.Sql_str = string.Format("{0}", item["sql_str"]);
                                _TaskRunTimeInfo.Error_Mail = string.Format("{0}", item["error_mail"]);
                                _TaskRunTimeInfo.Current_index = string.Format("{0}", item["current_index"]);
                                _TaskRunTimeInfo.Mail_address = string.Format("{0}", item["Mail_address"].ToString());
                                _TaskRunTimeInfo.Task_DB = string.Format("{0}", item["taskdb"].ToString());


                                //创建任务队列
                                taskQueue.Add(_TaskRunTimeInfo);
                                Thread.Sleep(500);//一秒插入一条
                                Console.WriteLine($"insert-----Task Status：{taskQueue.IsWaitAdd()}");
                                while (taskQueue.IsWaitAdd())//有待处理任务
                                {
                                    Console.WriteLine("insert-----Task Start Block!");
                                    SpinWait.SpinUntil(() => !taskQueue.IsWaitAdd());
                                }

                                //队列插入完成，更新最后执行时间
                                var _return_int = _BaseDAL.SubmitTaskRunTimeInfo(_TaskRunTimeInfo.Id);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("Task Run Submit ERROR：" + ex.ToString());
                }
            });

            var _RunByService_1 = true;
            //消费队列
            while (_RunByService_1)
            {

                Thread.Sleep(8000);     //检测消费队列的轮询秒数

                try
                {
                    var list = taskQueue.GetQueue();
                    Console.WriteLine("Tips-----start run to do list：" + ((list == null) ? "0" : list.Count().ToString()));
                    if (list != null)
                    {
                        Console.WriteLine($"Tips-----object：{taskQueue.IsWaitAdd()} have already list:{string.Join(",", list)}");

                        foreach (var item in list)
                        {
                            //如手工执行，则让服务不轮询既可
                            if (task_id != "")
                            {
                                _RunByService_1 = false;
                            }

                            DataRunScript dataRunScript = new DataRunScript();//实例化一个写入数据采集方法
                            dataRunScript.TaskCallBack += Accomplish;         //绑定完成任务要调用的委托回调方法

                            Thread thread = new Thread(new ParameterizedThreadStart(dataRunScript.Run));
                            thread.IsBackground = true;
                            thread.Start(item);
                        }

                        taskQueue.Complete();
                        Console.WriteLine("Tips-----task is submited!");
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("Task Run Customer ERROR：" + ex.ToString());
                }
            }
            #endregion
        }
        //完成任务时需要调用
        public static void Accomplish()
        {
            Console.WriteLine("TaskCallBack Complete!");

            //接收到完成，将队列提交一下
            taskQueue.Complete();
        }
    }
}
